﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web.Mvc;
using BookShop.BLL;
using BookShop.DTO;
using BookShop.Library.Constant;
using BookShop.Site.Models;
using Newtonsoft.Json;

namespace BookShop.Site.Controllers
{
    public class AccountController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public ActionResult Login(string previousUrl)
        {
            ViewBag.PreviousUrl = previousUrl;
            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Login(string username, string password, string previousUrl)
        {
            try
            {
                var customer = CustomerService.Login(username, password);
                if (customer == null)
                {
                    ModelState.AddModelError("", "Thông tin đăng nhập không chính xác!");
                    return View();
                }
                Session.Add(SessionKey.Customer, customer);
                var cartItemList = JsonConvert.DeserializeObject<List<CartItem>>(customer.PreviousCart ?? string.Empty) ??
                                   new List<CartItem>();
                if (cartItemList.Count > 0)
                {
                    Session.Add(SessionKey.ShoppingCart, cartItemList);
                }
                if (!string.IsNullOrWhiteSpace(previousUrl))
                {
                    return Redirect(previousUrl);
                }
                return RedirectToAction("Index", "Home");
            }
            catch (Exception e)
            {
                ModelState.AddModelError("", e);
                return View();
            }
            finally
            {
                ViewBag.Username = username;
            }
        }

        public ActionResult LogOut()
        {
            if (Session[SessionKey.Customer] != null)
            {
                var customer = (Customer)Session[SessionKey.Customer];

                if (Session[SessionKey.ShoppingCart] != null)
                {
                    if (customer != null)
                    {
                        var cartItemList = (List<CartItem>)Session[SessionKey.ShoppingCart];
                        if (cartItemList != null && cartItemList.Count > 0)
                        {
                            string message;
                            customer.PreviousCart = JsonConvert.SerializeObject(cartItemList);
                            CustomerService.Update(customer, out message);
                        }
                    }
                    Session.Remove(SessionKey.ShoppingCart);
                }
                Session.Remove(SessionKey.Customer);
            }
            return RedirectToAction("Index", "Home");
        }

        public ActionResult PersonalInfomation(long customerId)
        {
            if (Session[SessionKey.Customer] == null)
            {
                return RedirectToAction("Login", new { previousUrl = Url.Action("PersonalInfomation", new { customerId }) });
            }
            var customer = CustomerService.GetById(customerId);
            if (customer == null)
            {
                return RedirectToAction("Index");
            }
            return View(customer);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult PersonalInfomation(long customerId, string email, string birthdate, string address,
            string phone, string fullName)
        {
            if (Session[SessionKey.Customer] == null)
            {
                return RedirectToAction("Login", new { previousUrl = Url.Action("PersonalInfomation", new { customerId }) });
            }
            var customer = CustomerService.GetById(customerId);
            if (customer == null)
            {
                return RedirectToAction("Index");
            }
            string message;
            customer.Email = email;
            DateTime newBirthdate;
            var isValidBirthdate = DateTime.TryParse(birthdate, CultureInfo.CreateSpecificCulture("vi-VN"),
                DateTimeStyles.None, out newBirthdate);
            if (isValidBirthdate)
            {
                customer.Birthdate = newBirthdate;
            }
            customer.Address = address;
            customer.Phone = phone;
            customer.FullName = fullName;
            customer = CustomerService.Update(customer, out message);
            if (customer == null)
            {
                return RedirectToAction("Error", "Home");
            }
            return View(customer);
        }

        public ActionResult OrderHistory(long customerId)
        {
            if (Session[SessionKey.Customer] == null)
            {
                return RedirectToAction("Login", new { previousUrl = Url.Action("OrderHistory", new { customerId }) });
            }
            var customer = CustomerService.GetById(customerId);
            if (customer == null)
            {
                return RedirectToAction("Index");
            }
            var model = OrderService.GetByCustomerId(customerId).OrderByDescending(o => o.CreateTime).ToList();
            return View(model);
        }

        public ActionResult OrderHistoryDetail(long orderId)
        {
            var model = new OrderCartItemListModel { IsShoppingCartPage = false, CartItems = new List<CartItem>()};
            var order = OrderService.GetById(orderId);
            if (order != null)
            {
                var orderDetailList = OrderDetailService.GetByOrderId(orderId);
                foreach (var orderDetail in orderDetailList)
                {
                    var book = BookService.GetById(orderDetail.BookId) ?? new Book();
                    book = BookService.UpdateNotMappedField(book);
                    var cartItem = new CartItem
                    {
                        Book = book,
                        Id = DateTime.Now.Ticks,
                        Quantity = orderDetail.Quantity,
                        UnitPrice = orderDetail.UnitPrice.HasValue ? orderDetail.UnitPrice.Value : book.Price
                    };
                    model.CartItems.Add(cartItem);
                }
                ViewBag.OrderCreateDate = order.CreateTime.ToString("d", CultureInfo.CreateSpecificCulture("vi-VN"));
                ViewBag.OrderId = order.Id;
            }
            return View(model);
        }

        public ActionResult SignUp()
        {
            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult SignUp(string email, string fullName, string username, string password)
        {
            string message;
            var customer = new Customer
            {
                Email = email,
                FullName = fullName,
                Username = username,
                Password = password,
                Status = CustomerStatus.Active
            };
            var addResult = CustomerService.Add(customer, out message);
            if (addResult != null)
            {
                return RedirectToAction("Login");
            }
            ViewBag.AddEmail = email ?? string.Empty;
            ViewBag.AddFullName = fullName ?? string.Empty;
            ViewBag.AddUsername = username ?? string.Empty;
            TempData[AlertMessage.TempDataKey] = message.Replace(",", ", ");
            return View();
        }
    }
}
